package com.project.base.baseproject.AppCustoms.SelectImageActivity;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.TextView;

import com.jaeger.library.StatusBarUtil;
import com.makeramen.roundedimageview.RoundedImageView;
import com.project.base.baseproject.Activity.BaseActivity.BaseActivity;
import com.project.base.baseproject.AppCustoms.MyApplication.MyApplication;
import com.project.base.baseproject.AppCustoms.SelectImageActivity.BangBangPhoto;
import com.project.base.baseproject.AppCustoms.SelectImageActivity.MuliteSelectImageAdapter;
import com.project.base.baseproject.AppCustoms.Tool.ToastUtil;
import com.project.base.baseproject.R;
import com.project.base.baseproject.Utikles.Constant.Constant;
import com.project.base.baseproject.Utikles.ThirdParty.RunInMainThread.UIKit;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//图片多选
public class MuliteSelectImageActivity extends BaseActivity implements MuliteSelectImageAdapter.OnRecyclerViewItemClickListener, View.OnClickListener {
    //数据源
    MuliteSelectImageAdapter muliteSelectImageAdapter;
    //当前所有的图片
    ArrayList<BangBangPhoto> bangBangPhotos;
    //所有相册对象
    Map<String, BangBnagBucket> bangBnagBucketMap;
    //最大选择数量
    int maxSelectNumber = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mulite_select_image_layout);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.white),0);
        //init
        muliteSelectImageAdapter = new MuliteSelectImageAdapter(new ArrayList<BangBangPhoto>());
        bangBangPhotos = new ArrayList<>();
        bangBnagBucketMap = new HashMap<>();
        if(getIntent() != null)
            maxSelectNumber = getIntent().getIntExtra("maxSelectNumber",9);
        //配置表格视图
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.common_listview);
        RecyclerView.LayoutManager mLayoutManager2 = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
        // 设置布局管理器
        recyclerView.setLayoutManager(mLayoutManager2);
        recyclerView.setAdapter(muliteSelectImageAdapter);
        muliteSelectImageAdapter.setOnItemClickListener(this);
        bangBnagBucketMap = getBucketList();
        //默认获取第一个相册的所有图片
        String bucketId = "";
        for (Map.Entry<String ,BangBnagBucket> entry : bangBnagBucketMap.entrySet()) {
            bucketId = entry.getKey();
            break;
        }
        bangBangPhotos = getPhotoList(bucketId);
        muliteSelectImageAdapter.updateData(bangBangPhotos);
        //设置点击事件
        findViewById(R.id.moreselect).setOnClickListener(this);
        findViewById(R.id.return_btn).setOnClickListener(this);
        findViewById(R.id.finish_btn).setOnClickListener(this);
        findViewById(R.id.look_btn).setOnClickListener(this);
        //设置当前数量
        setCurrNumberInfo();
    }
    //设置当前数量
    private void setCurrNumberInfo() {
        RoundedImageView messageNumberBg = (RoundedImageView) findViewById(R.id.messageNumberBg);
        TextView messageNumber = (TextView) findViewById(R.id.messageNumber);
        if(getSelectedNumber() == 0) {
            messageNumberBg.setVisibility(View.GONE);
            messageNumber.setVisibility(View.GONE);
        } else {
            messageNumberBg.setVisibility(View.VISIBLE);
            messageNumber.setVisibility(View.VISIBLE);
            messageNumber.setText(getSelectedNumber()+"");
        }
    }
    public static Map<String, BangBnagBucket> getBucketList() {
        Map<String, BangBnagBucket> bucketMap = new HashMap<>();
        ContentResolver contentResolver = MyApplication.getInstance().getContentResolver();
        try {
            String columns[] = new String[]{
                    MediaStore.Images.Media._ID,
                    MediaStore.Images.Media.BUCKET_ID,
                    MediaStore.Images.Media.DATA,
                    MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
            Cursor cursor = contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, null);
            if (null == cursor) {
                return bucketMap;
            }
            if (cursor.moveToFirst()) {
                int photoPathIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                int bucketNameIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
                int bucketIdIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_ID);
                do {
                    String photoPath = cursor.getString(photoPathIndex);
                    String bucketName = cursor.getString(bucketNameIndex);
                    String bucketId = cursor.getString(bucketIdIndex);

                    BangBnagBucket bucketBean;
                    if (bucketMap.containsKey(bucketId)) {
                        bucketBean = bucketMap.get(bucketId);
                        bucketBean.setPhotoCount(bucketBean.getPhotoCount() + 1);
                    } else {
                        bucketBean = new BangBnagBucket();
                        bucketBean.setBucketId(bucketId);
                        bucketBean.setBucketName(bucketName);
                        bucketBean.setThumbPath(photoPath);
                        bucketBean.setPhotoCount(1);
                        bucketMap.put(bucketId, bucketBean);
                    }
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            UIKit.runOnMainThreadAsync(new Runnable() {
                @Override
                public void run() {
                    ToastUtil.show(MyApplication.getInstance(),"图片获取失败");
                }
            });
        }
        return bucketMap;
    }
    //获取指定bucket下的所有图片
    public ArrayList<BangBangPhoto> getPhotoList(String bucketId) {
        ArrayList<BangBangPhoto> photoBeen = new ArrayList<>();
        ContentResolver contentResolver = MyApplication.getInstance().getContentResolver();
        try {
            String columns[] = new String[]{
                    MediaStore.Images.Media._ID,
                    MediaStore.Images.Media.BUCKET_ID,
                    MediaStore.Images.Media.DATA,
                    MediaStore.Images.Media.DISPLAY_NAME,
                    MediaStore.Images.Media.SIZE,
                    MediaStore.Images.Media.DATE_TAKEN,//拍摄时间
                    MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
            Cursor cursor = contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
                    MediaStore.Images.Media.BUCKET_ID + " =?", new String[]{bucketId},
                    MediaStore.Images.Media.DATE_TAKEN + " DESC");//按拍摄时间的降序排序
            if (cursor != null && cursor.moveToFirst()) {
                int photoIdIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
                int photoNameIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME);
                int photoSizeIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE);
                int photoPathIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                int dateTakenIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_TAKEN);
                do {
                    long photoId = cursor.getLong(photoIdIndex);
                    String photoPath = cursor.getString(photoPathIndex);
                    String photoName = cursor.getString(photoNameIndex);
                    int dateTaken = cursor.getInt(dateTakenIndex);
                    long photoSize = cursor.getLong(photoSizeIndex);
                    //组建对象
                    BangBangPhoto photoBean = new BangBangPhoto();
                    photoBean.setLocalPath(photoPath);
                    photoBeen.add(photoBean);
                } while (cursor.moveToNext());
            }
            return photoBeen;
        } catch (Exception e) {
            UIKit.runOnMainThreadAsync(new Runnable() {
                @Override
                public void run() {
                    ToastUtil.show(MyApplication.getInstance(),"图片获取失败");
                }
            });
        }
        return photoBeen;
    }
    @Override
    public void imageClicked(View view, BangBangPhoto bangBangPhoto) {
        if(getSelectedNumber() > maxSelectNumber) {
            ToastUtil.show(this,"已到最大选择数量");
            return;
        }
        bangBangPhoto.setSelected(!bangBangPhoto.isSelected());
        muliteSelectImageAdapter.updateData(bangBangPhotos);
        setCurrNumberInfo();
    }
    //获得当前一共选择了多少张
    private int getSelectedNumber() {
        int count = 0;
        for (BangBangPhoto bang : bangBangPhotos) {
            if(bang.isSelected())
                count++;
        }
        return count;
    }
    //获取当前选中的所有图片
    private ArrayList<BangBangPhoto> getSelectedPhoto() {
        ArrayList<BangBangPhoto> array = new ArrayList();
        for (BangBangPhoto bang : bangBangPhotos) {
            if(bang.isSelected()) {
                BangBangPhoto temp = new BangBangPhoto();
                temp.setLocalPath(bang.getLocalPath());
                temp.setSelected(bang.isSelected());
                array.add(temp);
            }
        }
        return array;
    }
    //点击事件
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //选择相册
            case R.id.return_btn:
                Intent intent = new Intent(this,MuliteSelectBucketActivity.class);
                startActivityForResult(intent, Constant.MULITE_SELECT_BUCKET_REQUEST_CODE);
                break;
            //取消
            case R.id.moreselect:
                finish();
                break;
            //预览
            case R.id.look_btn:
                Intent intent1 = new Intent(this,MuliteSelectBorwseActivity.class);
                if(getSelectedNumber() == 0)
                    return;
                intent1.putExtra("browseImage",(Serializable) getSelectedPhoto());
                startActivityForResult(intent1,Constant.MULITE_SELECT_BROWSE_REQUEST_CODE);
                break;
            //完成
            case R.id.finish_btn:
                if(getSelectedNumber() == 0) {
                    ToastUtil.show(this,"你还没有选择任务图片");
                    return;
                }
                Intent intent2 = new Intent();
                intent2.putExtra("selectImage",(Serializable) getSelectedPhoto());
                setResult(RESULT_OK,intent2);
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //多图选中 选择相册
        if(requestCode == Constant.MULITE_SELECT_BUCKET_REQUEST_CODE) {
            if(resultCode == RESULT_OK) {
                String bucketId = data.getStringExtra("bucketId");
                bangBangPhotos = getPhotoList(bucketId);
                muliteSelectImageAdapter.updateData(bangBangPhotos);
                setCurrNumberInfo();
            }
        }
        //多图选中 预览
        if(requestCode == Constant.MULITE_SELECT_BROWSE_REQUEST_CODE) {
            if(resultCode == RESULT_CANCELED) {
                //处理好被选中的图片
                ArrayList<BangBangPhoto> photos = (ArrayList<BangBangPhoto>) data.getSerializableExtra("selectImage");
                for (BangBangPhoto bang : photos) {
                    for (BangBangPhoto bangBang: bangBangPhotos) {
                        if(bang.getLocalPath().equals(bangBang.getLocalPath())) {
                            bangBang.setSelected(bang.isSelected());
                        }
                    }
                }
                muliteSelectImageAdapter.updateData(bangBangPhotos);
                setCurrNumberInfo();
            }
            if(resultCode == RESULT_OK) {
                Intent intent1 = new Intent();
                ArrayList<BangBangPhoto> photos = (ArrayList<BangBangPhoto>) data.getSerializableExtra("selectImage");
                ArrayList<BangBangPhoto> selectImage = new ArrayList<>();
                for (BangBangPhoto bang : photos) {
                    if(bang.isSelected() == true)
                        selectImage.add(bang);
                }
                intent1.putExtra("selectImage",(Serializable) selectImage);
                setResult(RESULT_OK,intent1);
                finish();
            }
        }
    }
}
